package service

import (
	"context"
	"encoding/json"
	"github.com/zeromicro/go-zero/core/logx"
	"gozero-demo/internal/constants"
	"gozero-demo/internal/repo/mysql"
	"gozero-demo/internal/svc"
	"gozero-demo/internal/types"
	"os"
	"path/filepath"
	"runtime"
)

type SubjectService struct {
	logx.Logger
	ctx         context.Context
	svcCtx      *svc.ServiceContext
	subjectRepo *mysql.SubjectRepo
}

func NewSubjectService(ctx context.Context, svcCtx *svc.ServiceContext) *SubjectService {
	return &SubjectService{
		Logger:      logx.WithContext(ctx),
		ctx:         ctx,
		svcCtx:      svcCtx,
		subjectRepo: mysql.NewSubjectRepo(ctx, svcCtx),
	}
}

// 方式三
func (s *SubjectService) GetSubjectConfig3() []types.SubjectData {
	return constants.SubjectDataStruct
}

// 方式二
func (s *SubjectService) GetSubjectConfig2() ([]types.SubjectData, error) {
	var structData []types.SubjectData
	if err := json.Unmarshal([]byte(constants.SubjectDataJson), &structData); err != nil {
		return nil, err
	}
	return structData, nil
}

// 方式一:不推荐
func (s *SubjectService) GetSubjectConfig1() ([]types.SubjectData, error) {
	// 获取当前代码文件所在的目录
	_, currentFile, _, _ := runtime.Caller(0)
	dir := filepath.Dir(currentFile)

	// 构建相对于当前代码文件所在目录的路径
	filePath := filepath.Join(dir, "data", "subject_config.json")

	// 读取JSON文件
	jsonData, err := os.ReadFile(filePath)
	if err != nil {
		return nil, err
	}

	// 解析JSON
	var structData []types.SubjectData
	if err := json.Unmarshal(jsonData, &structData); err != nil {
		return nil, err
	}

	return structData, nil
}
